import axios from 'axios'
import { createHashHistory } from 'history';
import { Message } from '@alifd/next';

// 创建axios实例
const service = axios.create({
  timeout: 150000// 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  config.url = '/databus' + config.url
  config.ignoreError = true
  return config
}, error => {
  console.error(error)
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    let msg = "", title = "";
    // out of the range of 2xx
    if (error.response) {
      if(403 == error.response.status) {
        createHashHistory().push('/403');
      } else if(error.response.data && error.response.data.errors) {
        msg = error.response.data.errors[0].errmsg;
      } else {
        msg = error.response.statusText;
      }
    } else if (error.request) {
      msg = "服务器无响应";
    } else {
      msg = error.message;
    }

    if(error.config.ignoreError !== true) {
      Message.show({
          type: 'error',
          title: (error.response?error.response.status:'') + '(' + error.config.url + ')',
          content: msg,
          duration: 3000
      });
    }
    
    return Promise.reject(error)
  }
)

export default service
